#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QNetworkDatagram>
#include <fstream>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //创建出socket对象
    socket = new QUdpSocket(this);
    this->setWindowTitle("服务器");
    QFont font;
    font.setPixelSize(20);
    ui->listWidget->setFont(font);

    //连接信号槽
    connect(socket, &QUdpSocket::readyRead, this, &Widget::processRequest);

    //绑定端口号（0～65535）
    bool ret = socket->bind(QHostAddress::Any, 8080);
    if(!ret)
    {
        QMessageBox::critical(this, "服务器启动出错", socket->errorString());
        return;
    }
    QMessageBox::information(this, "服务器启动成功", "回显已经准备就绪");
}

void Widget::processRequest()
{
    const QNetworkDatagram& requestDatagram = socket->receiveDatagram();
    QString request = requestDatagram.data();
    const QString response = process(request);
    QNetworkDatagram responseDatagram(response.toUtf8(), requestDatagram.senderAddress(), requestDatagram.senderPort());
    socket->writeDatagram(responseDatagram);
    QString info_1 = "[ " + requestDatagram.senderAddress().toString() + " : " + QString::number(requestDatagram.senderPort())
                   + "  rep: " + request + "\n";
    QString info_2 = "[ " + requestDatagram.senderAddress().toString() + " : " + QString::number(requestDatagram.senderPort())
                     + "  reps: " + response + "___added sucessfully";
    std::ofstream output;
    output.open("/Users/wangjiale/Desktop/code/qt/udp_echo_server/datas.txt", std::ios::app);
    if(!output.is_open())
    {
        qDebug() << "open data.txt fail";
    }
    output << info_1.toStdString();
    output.close();
    ui->listWidget->addItem(info_2);
}

const QString Widget::process(const QString& request)
{
    QString request_return = request + "_added successfully";
    return request_return;
}

Widget::~Widget()
{
    delete ui;
}
